package com.lib.common.widget.recyclerView.drag

import android.view.GestureDetector
import android.view.MotionEvent
import androidx.core.view.GestureDetectorCompat
import androidx.recyclerview.widget.RecyclerView

/**
 * Copyright (C), 2020-2020, 享物说
 * FileName: OnDragRecyclerItemClickListener
 * Author: keanbin
 * Date: 2020-02-11 23:02
 * Description: 可拖拽 的  RecyclerView.OnItemTouchListener
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
abstract class OnDragRecyclerItemClickListener(val recyclerView: RecyclerView) :
    RecyclerView.OnItemTouchListener {
    private val mGestureDetector: GestureDetectorCompat =
        GestureDetectorCompat(recyclerView.context, ItemTouchHelperGestureListener());

    override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
        mGestureDetector.onTouchEvent(e)
        return false
    }

    override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
        mGestureDetector.onTouchEvent(e)
    }

    override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}

    private inner class ItemTouchHelperGestureListener : GestureDetector.SimpleOnGestureListener() {
        override fun onSingleTapUp(e: MotionEvent): Boolean {
            val child = recyclerView.findChildViewUnder(e.x, e.y)
            if (child != null) {
                val vh = recyclerView.getChildViewHolder(child)
                onItemClick(vh)
            }
            return true
        }

        override fun onLongPress(e: MotionEvent) {
            val child = recyclerView.findChildViewUnder(e.x, e.y)
            if (child != null) {
                val vh = recyclerView.getChildViewHolder(child)
                onItemLongClick(vh)
            }
        }
    }

    abstract fun onItemClick(vh: RecyclerView.ViewHolder)

    abstract fun onItemLongClick(vh: RecyclerView.ViewHolder)
}